* File to create lags of pollution at the zip-daily level


***Inputs:
* $Data/GameUser_zd.dta, clear
* $Data/UserMonitorMatch.dta
* $Data/aqs_sites_dailyid.dta
* $Data/daily_PM2p5_1318.dta

***Output:
* $Data/Lag`lag'dailypm_zd.dta, lag=1:7
* $Data/Lead`lead'dailypm_zd.dta, lead=1:7


forval lag = 1(1)7 {
use  $Data/GameUser_zd.dta , clear

rename date date_play

	gen date = date-`lag'
	
	joinby zip using $Data/UserMonitorMatch.dta
	
	merge m:1 id using $Data/aqs_sites_dailyid.dta
	drop if _merge ==2
	drop _merge
   
	merge m:1 statecode countycode sitenumber date using $Data/daily_PM2p5_1318.dta

	drop if _merge ==2 // 

	drop _merge


	***3. CALCULATE THE WEIGHTED AVERAGE OF PM2p5 BY ZIPCODE AND DATE***


	gen weight = 1/(aq_dist^2)


	gen distance_weight = mean_pollution*weight
	by zip date, sort: egen sumdistance_pm25 = total(distance_weight)
	by zip date, sort: egen sum_weight = total(weight)

	gen lag`lag'_dailypm25 = sumdistance_pm25/sum_weight

	drop date
	
	rename date_play date
	
	
	
	keep lag date zip 

	
	duplicates drop
	
	save $Data/Lag`lag'dailypm_zd.dta, replace
	
	}

	
	
	
	
	
	forval lead = 1(1)7 {
use  $Data/GameUser_zd.dta , clear

rename date date_play

	gen date = date+`lead'
	
	joinby zip using $Data/UserMonitorMatch.dta
	
	merge m:1 id using $Data/aqs_sites_dailyid.dta
	drop if _merge ==2
	drop _merge
   
	merge m:1 statecode countycode sitenumber date using $Data/daily_PM2p5_1318.dta

	drop if _merge ==2 // 

	drop _merge


	***3. CALCULATE THE WEIGHTED AVERAGE OF PM2p5 BY ZIPCODE AND DATE***


	gen weight = 1/(aq_dist^2)


	gen distance_weight = mean_pollution*weight
	by zip date, sort: egen sumdistance_pm25 = total(distance_weight)
	by zip date, sort: egen sum_weight = total(weight)

	gen lead`lead'_dailypm25 = sumdistance_pm25/sum_weight

	drop date
	
	rename date_play date
	
	
	
	keep lead date zip 

	
	duplicates drop
	
	save $Data/Lead`lead'dailypm_zd.dta, replace
	}
	
